﻿Imports System.Text
Imports System.Runtime.CompilerServices

Module Extensions

	<Extension()>
	Public Function ToASCII(UTF8String As String) As String
		Dim ASCII As New ASCIIEncoding()
		Dim byteArray As Byte() = Encoding.UTF8.GetBytes(UTF8String)
		Dim ASCIIArray As Byte() = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray)
		'Dim finalString As String = ASCII.GetString(ASCIIArray)
		Dim finalString As String = ASCII.GetString(byteArray)
		Return finalString
	End Function

	'http://www.codeproject.com/Articles/6441/Binary-to-Text-Encode-Decode-Class
	<Extension()>
	Public Function ToQuotedPrintable(UnicodeString As String) As String
		If String.IsNullOrEmpty(UnicodeString) Then
			Return Nothing
		Else

			Dim ASCII As Integer
			Dim myBytes As Byte()
			Dim EncodedChar As String
			Dim sb As New StringBuilder

			For i = 0 To UnicodeString.Length - 1
				ASCII = AscW(UnicodeString(i))
				If ASCII < 32 OrElse ASCII = 61 OrElse ASCII > 126 Then
					myBytes = Encoding.UTF8.GetBytes(UnicodeString(i))
					For Each myByte In myBytes
						EncodedChar = Hex(myByte).ToUpper
						If EncodedChar.Length = 1 Then
							EncodedChar = "0" & EncodedChar
						End If
						sb.Append("=" & EncodedChar)
					Next
				Else
					sb.Append(UnicodeString(i))
				End If
			Next

			Return sb.ToString

			'Return System.Convert.ToBase64String(Encoding.UTF8.GetBytes(UnicodeString))

			'If StringWithLineBreaks.Contains(Environment.NewLine) Then
			'	Return StringWithLineBreaks.Replace(Environment.NewLine, "=0D=0A=" & Environment.NewLine)
			'Else
			'	Return StringWithLineBreaks
			'End If
		End If

	End Function

	<Extension()>
	Public Function EscapeParameters(UnescapedString As String) As String
		If String.IsNullOrEmpty(UnescapedString) Then
			Return Nothing
		Else
			Return UnescapedString.Replace(";", "\;")
		End If
	End Function

	<Extension()>
	Public Function IsUnicode(TestString As String) As Boolean
		If String.IsNullOrEmpty(TestString) Then
			Return False
		Else
			Return TestString.ToCharArray.AsParallel.Any(Function(x As Char) AscW(x) < 32 OrElse AscW(x) = 61 OrElse AscW(x) > 126)
		End If
	End Function
End Module
